﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.IO;
using Microsoft.Xna.Framework.Media;
using System.Windows.Navigation;
using ImageTools.Helpers;
using ImageTools;

namespace Nok_Air
{
    public partial class BoardingPassPage : PhoneApplicationPage
    {
        private string FlightIndexPar = "";
        private string PassengersIndexPar = "";
        public BoardingPassPage()
        {
            InitializeComponent();
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(BoardingPassPage_Loaded);           
        }

        private void ShowImage(WriteableBitmap writeableBitmap)
        {
            Dispatcher.BeginInvoke(delegate
            {
                BarcodeImg.Source = writeableBitmap;
              //  textBlock1.Visibility = Visibility.Collapsed;
            });
        }

        private void DownloadGifImage(string url)
        {
            var webClient = new WebClient();
            webClient.OpenReadCompleted += webClientOpenReadCompleted;
            webClient.OpenReadAsync(new Uri(url, UriKind.Absolute));
        }

        private void webClientOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            var b = new byte[e.Result.Length];
            e.Result.Read(b, 0, b.Length);
            if (b[0] == 71 && b[1] == 73 && b[2] == 70)
            {
                // File is a GIF, we need to convert it!
                var image = new ImageTools.Image();
                var gifDecoder = new ImageTools.IO.Gif.GifDecoder();
                gifDecoder.Decode(image, new MemoryStream(b));
                ShowImage(ToBitmap(image));
            }
            else
            {
                // File is not a GIF...
                e.Result.Close();
            }
        }

        public static WriteableBitmap ToBitmap(ImageBase image)
        {
            Guard.NotNull(image, "image");
            var bitmap = new WriteableBitmap(image.Width, image.Height);
            ImageBase temp = image;
            byte[] pixels = temp.GetPixels();
            int[] raster = bitmap.Pixels;
            Buffer.BlockCopy(pixels, 0, raster, 0, pixels.Length);
            for (int i = 0; i < raster.Length; i++)
            {
                int abgr = raster[i];
                int a = (abgr >> 24) & 0xff;
                float m = a / 255f;
                int argb = a << 24 |
                           (int)((abgr & 0xff) * m) << 16 |
                           (int)(((abgr >> 8) & 0xff) * m) << 8 |
                           (int)(((abgr >> 16) & 0xff) * m);
                raster[i] = argb;
            }
            bitmap.Invalidate();
            return bitmap;
        }












        void BoardingPassPage_Loaded(object sender, RoutedEventArgs e)
        {
            int _indexFlight = int.Parse(FlightIndexPar);
            int _indexPassengers = int.Parse(PassengersIndexPar);
            if (App.ViewModel.GetPassengersResult.Flights[_indexFlight].Passengers[_indexPassengers].Barcode == null)
            {
                return;
            }
            DownloadGifImage("http://dev.nokair.com:8080/NokCheckinService/" + App.ViewModel.GetPassengersResult.Flights[_indexFlight].Passengers[_indexPassengers].Barcode);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (NavigationContext.QueryString.TryGetValue("FlightIndex", out FlightIndexPar) && NavigationContext.QueryString.TryGetValue("PassengersIndex", out PassengersIndexPar))
            {
                int _indexFlight = int.Parse(FlightIndexPar);
                int _indexPassengers = int.Parse(PassengersIndexPar);
                FlightPanel.DataContext = App.ViewModel.GetPassengersResult.Flights[_indexFlight];
                PassengerPanel.DataContext = App.ViewModel.GetPassengersResult.Flights[_indexFlight].Passengers[_indexPassengers];
             //   PassengerListBox.ItemsSource = App.ViewModel.GetPassengersResult.Flights[_index].Passengers;
              
            }
        }

        private void nokAppButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
			NavigationService.GoBack();
        }

        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                WriteableBitmap wb = new WriteableBitmap(LayoutRoot, null);
                MemoryStream stream = new MemoryStream((int)LayoutRoot.ActualHeight * (int)LayoutRoot.ActualWidth * 4);
                wb.SaveJpeg(stream, (int)LayoutRoot.ActualWidth, (int)LayoutRoot.ActualHeight, 0, 100);
                stream.Seek(0, 0);
                MediaLibrary ml = new MediaLibrary();

                int _indexFlight = int.Parse(FlightIndexPar);
                int _indexPassengers = int.Parse(PassengersIndexPar);
                string fileName = App.ViewModel.GetPassengersResult.Flights[_indexFlight].Passengers[_indexPassengers].BookingNo;
                ml.SavePicture(fileName + PassengersIndexPar, stream);

                MessageBox.Show(App.ViewModel.SaveComplete);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
